package cn.jcet.controller.system;

import cn.jcet.config.shiro.ActiverUser;
import cn.jcet.constants.Constants;
import cn.jcet.constants.HttpStatus;
import cn.jcet.domain.Menu;
import cn.jcet.domain.SimpleUser;
import cn.jcet.dto.LoginBodyDto;
import cn.jcet.service.MenuService;
import cn.jcet.service.UserService;
import cn.jcet.vo.AjaxResult;
import cn.jcet.vo.MenuTreeVo;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 鲜磊
 * @Date 2021/1/18 23:08
 * 登录
 */
@RestController
@Log4j2
public class LoginController {


//    @Autowired
//    private UserService userService;

    @Autowired
    private MenuService menuService;

    /**
     * 用户登录
     * @param loginBodyDto
     * @param request
     * @return
     */
    @PostMapping("login/doLogin")
    public AjaxResult login(@RequestBody @Validated LoginBodyDto loginBodyDto, HttpServletRequest request){
        // 默认状态为成功
        AjaxResult ajaxResult = AjaxResult.success();
        // 获取用户名称和密码
        String username = loginBodyDto.getUsername();
        String password = loginBodyDto.getPassword();
        // 获取用户名和密码token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 获取shiro的安全验证
        Subject subject = SecurityUtils.getSubject();
        // 获取登录
        try {
            subject.login(token);
            // 获取当前会话的sessionId
            Serializable webToken = subject.getSession().getId();
            // 保存session的id
            ajaxResult.put(Constants.TOKEN,webToken);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("用户名或密码不正确",e);
            ajaxResult = AjaxResult.error(HttpStatus.ERROR,"用户名或密码不正确");
        }
        return ajaxResult;
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("login/getInfo")
    public AjaxResult getInfo(){
        // 验证凭证
        Subject subject = SecurityUtils.getSubject();

        ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
        // 默认成功
        AjaxResult ajax = AjaxResult.success();
        // 讲信息存入到域中
        ajax.put("username",activerUser.getUser().getUserName());
        ajax.put("picture", activerUser.getUser().getPicture());
        ajax.put("roles", activerUser.getRoles());
        ajax.put("permissions", activerUser.getPermissions());
        // 返回数据
        return ajax;
    }

    /**
     * 用户退出
     * @return
     */
    @PostMapping("login/logout")
    public AjaxResult logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return AjaxResult.success("用户退出成功！");
    }


    /**
     *  获取显示的菜单名称和路径
     * @return
     */
    @GetMapping("login/getMenus")
    public AjaxResult getMenu(){
        // 获取安全凭证
        Subject subject = SecurityUtils.getSubject();
        ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
        // 获取数据库中的状态
        boolean isAdmin = activerUser.getUser().getUserType().equals(Constants.USER_ADMIN);
        SimpleUser simpleUser = null;
        // 如果不是超级管理怎么查询
        if (!isAdmin){
            simpleUser = new SimpleUser(activerUser.getUser().getUserId(),activerUser.getUser().getUserName());
        }
        // 查询
        List<Menu> menus = menuService.selectMenuTree(isAdmin, simpleUser);
        // 创建一个保存新的菜单集合
        List<MenuTreeVo> menuVos = new ArrayList<>();
        for (Menu menu : menus) {
            menuVos.add(new MenuTreeVo(menu.getMenuId().toString(),menu.getPath()));
        }
        return AjaxResult.success(menuVos);
    }
}
